package com.base.vistter.iframe.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<Date> {

    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public WriteCellData<String> convertToExcelData(Date date, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        JsonFormat jsonFormat = contentProperty.getField().getAnnotation(JsonFormat.class);
        if (jsonFormat != null) {
            String format = jsonFormat.pattern();
            if (StringUtils.isNotEmpty(format)) {
                DateFormat df = new SimpleDateFormat(format);
                return new WriteCellData<String>(df.format(date));
            }
        }
        DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        return new WriteCellData<String>(dateFormat.format(date));
    }
}
